import {
  AreaChartOutlined,
  EllipsisOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import {
  Button,
  Dropdown,
  Form,
  Input,
  Modal,
  Space,
  Switch,
  Tag,
  Tooltip,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import { connect } from 'umi';
import { useAddKey } from '@/pages/hooks/index';
import React from 'react';
// import request from 'umi-request';
const { Search } = Input;
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}

type GithubIssueItem = {
  url: string;
  id: number;
  number: number;
  title: string;
  labels: {
    name: string;
    color: string;
  }[];
  state: string;
  comments: number;
  created_at: string;
  updated_at: string;
  closed_at?: string;
};

const list = (props: any) => {
  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>(
    'checkbox',
  );
  const [tit, setTit] = useState('新建');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [id, setId] = useState('');
  const [form] = Form.useForm();
  // 编辑
  const edit = (item: any) => {
    showModal();
    form.setFieldsValue({
      username: item.estate_name,
    });
    setTit('编辑');
    setId(item.id);
  };
  useEffect(() => {
    if (tit === '新建') {
      form.setFieldsValue({
        username: '',
      });
    }
  }, [tit]);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish = (values: any) => {
    console.log('Success:', values);
    if (tit === '新建') {
      props.dispatch({ type: 'house/ADDSECOND', values });
    } else {
      props.dispatch({ type: 'house/EDITSECOND', values, id });
    }

    setIsModalOpen(false);
  };
  // 删除
  const del = (item: any) => {
    props.dispatch({ type: 'house/DELSECOND', item });
  };
  // 新增
  const add = () => {
    showModal();
    setTit('新建');
  };
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '小区名称',
      dataIndex: 'estate_name',
    },
    {
      title: '标题',
      dataIndex: 'title',
      render: (item, record: any) => {
        const img =
          record.rec_position === 1 ? (
            <img
              src="http://fangadmin.shbwyz.com/static/images/rec.png"
              alt=""
            />
          ) : (
            ''
          );
        return (
          <React.Fragment>
            {item}
            {img}
            {record.img ? (
              <Tooltip
                title={
                  <img
                    className="ll-img"
                    src={`http://fangadmin.shbwyz.com${record.img}`}
                  ></img>
                }
              >
                <AreaChartOutlined />
              </Tooltip>
            ) : (
              ''
            )}
          </React.Fragment>
        );
      },
    },
    {
      title: '面积',
      dataIndex: 'acreage',
    },
    {
      title: '总价',
      dataIndex: 'ordid',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (item) => {
        return (
          <Switch
            checkedChildren="正常"
            unCheckedChildren="待审"
            defaultChecked={item === 1 ? true : false}
          ></Switch>
        );
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <Button onClick={() => edit(record)}>编辑</Button>,
        <Button onClick={() => del(record)}>删除</Button>,
      ],
    },
  ];
  console.log(props);
  // rowSelection object indicates the need for row selection
  const rowSelection: any = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows,
      );
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };
  // 搜索
  const onSearch = (value: string) => {
    console.log(value);
    props.dispatch({ type: 'house/secondSearch', value });
  };
  const actionRef = useRef<ActionType>();
  useEffect(() => {
    props.dispatch({ type: 'house/second' });
  }, []);
  return (
    <div>
      <Search
        placeholder="input search text"
        allowClear
        enterButton="Search"
        size="large"
        onSearch={onSearch}
      />
      <ProTable<GithubIssueItem>
        columns={columns}
        actionRef={actionRef}
        dataSource={useAddKey(props.list)}
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        cardBordered
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          onChange(value) {
            console.log('value: ', value);
          },
        }}
        rowKey="id"
        search={false}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
          onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        headerTitle="高级表格"
        toolBarRender={() => [
          <Button
            onClick={add}
            key="button"
            icon={<PlusOutlined />}
            type="primary"
          >
            新建
          </Button>,
          <Dropdown
            key="menu"
            menu={{
              items: [
                {
                  label: '1st item',
                  key: '1',
                },
                {
                  label: '2nd item',
                  key: '1',
                },
                {
                  label: '3rd item',
                  key: '1',
                },
              ],
            }}
          >
            <Button>
              <EllipsisOutlined />
            </Button>
          </Dropdown>,
        ]}
      />
      <Modal
        title={tit}
        open={isModalOpen}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          form={form}
        >
          <Form.Item
            label="小区名称"
            name="username"
            rules={[{ required: true, message: 'Please input your username!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              确定
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
const mapStateToProps = (state: any) => {
  console.log(state);

  return {
    list: state.house.secondList,
  };
};
export default connect(mapStateToProps)(list);
